/**
 * gislin
 * 2016年4月13日
 */
package io.chance.receiverlei.channel;

import io.chance.receiverlei.db.redis.StationService;
import lrq.common.ByteUnit;
import lrq.common.MyLog;
import org.apache.log4j.Logger;
import org.jboss.netty.buffer.BigEndianHeapChannelBuffer;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

public class MsgStoreHandler extends SimpleChannelUpstreamHandler {

    private static Logger log;
    private static File msgFile = new File("config/msgfile.dat");

    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
        if (log == null) {
            log = MyLog.getLogger(getClass().getName());
        }

        try {
            BigEndianHeapChannelBuffer r = (BigEndianHeapChannelBuffer) e.getMessage();
            byte[] dataByte = new byte[r.readableBytes()];
            r.readBytes(dataByte);
            //心跳包含mn，数据报文不包含
            String mn = ByteUnit.ConvertByteToInt8(dataByte[0]) + "";
            Logger msgLog = MyLog.getLogger("msg_" + mn);

            StationService.getInstance().updateStationDataReceiveTime(mn);
            ChannelManager.addDevice(mn + "", ctx.getChannel());//注册设备

            try (OutputStream os = new FileOutputStream(msgFile, true);) {
                os.write(dataByte);
            }
            catch (Exception e2) {
                log.error("e2", e2);
            }

            String strMSG = getMsgString(dataByte);
            msgLog.info("rec> " + strMSG);
        }
        catch (Exception e1) {
            log.error("e1", e1);
        }
    }

    private String getMsgString(byte[] data) {
        return MessageDecode.bytes2Hex(data);
    }
}
